import { callWithNuxt } from "#app";

/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-23 09:35:51
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-26 14:56:17
 * @FilePath: \vue3_nuxt_demo\composables\useHttpFetch.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
export interface IFetchOptions {
  headers?: Record<string, string>;
  [key: string]: any;
}

export interface IFetchResponse {
  code: number;
  data: any;
}

// 二次封装fetch方法
export const useHttpFetch = (url: string, opt: IFetchOptions) : Promise<IFetchResponse> => {
  // token
  const token = useCookie('token');
  // 提示消息
  const { $message } = useNuxtApp();

  const nuxtApp = useNuxtApp();
  // 添加请求头和token
  const headers = {
    ...opt.headers,
    ...(token.value ? {Authorization: `${token.value}`} : {}),
  }
  opt.headers = headers;

  return $fetch(url, {
    ...opt,
    baseURL: 'http://localhost:3000/', // 基本url
    timeout: 5000,
    server: false,
    onRequest({ request, options }) {
      // 设置请求头
    },
    onRequestError({ request, options, error }) {
      // 处理请求错误
    },
    onResponse({ request, response, options }) {
      // 处理响应数据
    },
    async onResponseError({ request, response, options }) {
      // 处理响应错误
      const { status } = response;
      
      if (status === 401) {
        $message.error('请先登录');
        await callWithNuxt(
          nuxtApp,
          navigateTo,
          [
                    "/login",
                    { replace:true,
                      redirectCode:401
                    }
                ]);
      }

      if (status === 500) {
        $message.error('服务器错误');
      }
      
    }
  });
}